#include "pslsimfunc.h"

#include <stdio.h>

void error(const char *msg)
{
    perror(msg);
    //exit(1);
}

int sendCmd(int socket, Command cmd)
{
    ComandPkg command;
    command.cmd = cmd;
    return sendCmdPkg(socket, command);
}

int sendCmdPkg(int socket, ComandPkg cmdPkg)
{
    return send(socket, (char*)&cmdPkg,  sizeof(ComandPkg), 0);
}

int sendCmdPkgEx(int socket, Command cmd, uint16_t objektId, uint16_t x_mm, uint16_t y_mm, uint16_t theta_grad)
{
    ComandPkg cpkg;
    cpkg.cmd = cmd;
    cpkg.kord.objektId = objektId; 
    cpkg.kord.xkordinate_mm = x_mm;
    cpkg.kord.ykordinate_mm = y_mm; 
    cpkg.kord.theta_grad = theta_grad;
    return sendCmdPkg(socket, cpkg);
}



int readin(int fd, char * buffer, int size)
{
    int n = 0;
    n = recv(fd, buffer, size, MSG_WAITALL);
    if (n < 0)
	error("ERROR reading from socket");
    return n;
}


int connectSocket(const char * hostname, int16_t portno)
{
    struct sockaddr_in serv_addr;
    struct hostent *hp;
    if ((hp = gethostbyname(hostname)) == 0) 
	error("gethostbyname");		



    memset((void *)&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family 	= AF_INET;
    serv_addr.sin_addr.s_addr 	= ((struct in_addr *)(hp->h_addr))->s_addr;
    serv_addr.sin_port 	= htons(portno);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
	error("ERROR opening socket");    
    if (connect(sockfd,(struct sockaddr *)  &serv_addr, sizeof(serv_addr)) == -1)
	error("could not connect connect");
    return sockfd;
}

